package com.kpx.app.wigdet;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;

import com.kpx.app.R;
import com.kpx.app.wigdet.NumberPicker.OnValueChangeListener;

import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;

/**
 * 双小时和分钟选择器（如9:30至18:30）
 */
public class HoursAndMinutesDoublePickDialog extends BaseDialog implements OnValueChangeListener {

    protected static final int MSG_RECOMPUTE_DIVIDER_POSITION = 0;
    protected static Activity mContext;
    private final View.OnClickListener dismissListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            dismiss();
        }
    };
    protected int START_YEAR = 1900, END_YEAR = 2100;
    protected int NOW_YEAR = 2100, NOW_MOUTH = 12, NOW_DAY = 1;
    protected ImageView topDivider;
    protected ImageView bottomDivider;
    protected NumberPicker hours_end;
    protected NumberPicker mins_end;
    protected NumberPicker hours_start;
    protected NumberPicker mins_start;
    protected String[] months_big = {"1", "3", "5", "7", "8", "10", "12"};
    protected final List<String> list_big = Arrays.asList(months_big);
    protected String[] months_little = {"4", "6", "9", "11"};
    protected final List<String> list_little = Arrays.asList(months_little);
    protected Button btn_sure;
    protected CharSequence positiveText;
    protected Button btn_cancel;
    protected CharSequence negativeText;
    protected CharSequence titleText;
    protected Calendar startCalendar;
    protected Calendar endCalendar;
    protected View.OnClickListener positiveClickListener;
    protected View.OnClickListener negativeClickListener;
    @SuppressLint("HandlerLeak")
    protected Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_RECOMPUTE_DIVIDER_POSITION:
                    if (Build.VERSION.SDK_INT > 11) {
                        topDivider.setY(msg.arg1);
                        bottomDivider.setY(msg.arg2);
                    } else {
                        LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                        params.topMargin = msg.arg1; // Your Y coordinate
                        topDivider.setLayoutParams(params);

                        params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                        params.topMargin = msg.arg2; // Your Y coordinate
                        bottomDivider.setLayoutParams(params);
                    }
                    break;
            }
        }
    };

    protected HoursAndMinutesDoublePickDialog(Context context) {
        super(context);
        // this.mContext = context;
    }

    protected HoursAndMinutesDoublePickDialog(Context context, Calendar instance) {
        this(context);
        startCalendar = instance;
    }

    public static long getFormatTime(Calendar c) {
        String parten = "00";
        DecimalFormat decimal = new DecimalFormat(parten);
        // 设置日期的显示
        Calendar calendar = c;
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DATE);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        int minute = calendar.get(Calendar.MINUTE);
        return calendar.getTimeInMillis();

    }

    public static int pixelsToDip(Resources res, int pixels) {
        final float scale = res.getDisplayMetrics().density;
        return (int) (pixels * scale + 0.5f);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.setContentView(R.layout.double_hours_minutes_picker_dlg_layout);
        setEndDate();
        findView();
        setListener();
        setDate(startCalendar, endCalendar);
        // 自定义代码在这里
        onCustomDisplayType();
    }

    protected void setEndDate() {
        try {
            Calendar cd = Calendar.getInstance();
            NOW_YEAR = cd.get(Calendar.YEAR);
            END_YEAR = NOW_YEAR;
            Log.v("tag", "END_YEAR----------" + END_YEAR);
            NOW_MOUTH = cd.get(Calendar.MONTH) + 1;
            Log.v("tag", "NOW_MOUTH----------" + NOW_MOUTH);
            NOW_DAY = cd.get(Calendar.DATE);
            Log.v("tag", "NOW_DAY----------" + NOW_DAY);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void onCustomDisplayType() {

    }

    private void setListener() {
        // 取消
       /* hours_start.setOnValueChangedListener(this);
        mins_start.setOnValueChangedListener(this);*/
        if (negativeClickListener != null) {
            btn_cancel.setOnClickListener(negativeClickListener);
        } else {
            btn_cancel.setOnClickListener(dismissListener);
        }
        if (positiveClickListener != null) {
            btn_sure.setOnClickListener(positiveClickListener);
        } else {
            btn_sure.setOnClickListener(dismissListener);
        }

    }

    private void findView() {
        hours_end = (NumberPicker) findViewById(R.id.numberPicker_hour);
        hours_end.setMaxValue(23);
        hours_end.setMinValue(0);
        hours_end.setFocusable(true);
        hours_end.setFocusableInTouchMode(true);

        hours_start = (NumberPicker) findViewById(R.id.numberPicker_hour2);
        hours_start.setMaxValue(23);
        hours_start.setMinValue(0);
        hours_start.setFocusableInTouchMode(true);

        mins_end = (NumberPicker) findViewById(R.id.numberPicker_minute);
        mins_end.setDataFormat(true);
        mins_end.setMinValue(0);
        mins_end.setMaxValue(59);
        mins_end.setFocusable(true);
        mins_end.setFocusableInTouchMode(true);

        mins_start = (NumberPicker) findViewById(R.id.numberPicker_minute2);
        mins_start.setDataFormat(true);
        mins_start.setMinValue(0);
        mins_start.setMaxValue(59);
        mins_start.setFocusable(true);
        mins_start.setFocusableInTouchMode(true);

        topDivider = (ImageView) findViewById(R.id.picker_bg_divider_top);
        bottomDivider = (ImageView) findViewById(R.id.picker_bg_divider_bottom);

        // 自动填充区域
        final RelativeLayout layout = (RelativeLayout) findViewById(R.id.linearLayout_pickers_container);
        layout.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                LayoutParams rlParamsTop = (LayoutParams) topDivider.getLayoutParams();
                rlParamsTop.width = layout.getWidth();
                topDivider.setLayoutParams(rlParamsTop);

                LayoutParams rlParamsBottom = (LayoutParams) bottomDivider.getLayoutParams();
                rlParamsBottom.width = layout.getWidth();
                bottomDivider.setLayoutParams(rlParamsBottom);

                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                    layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                } else {
                    layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }

            }
        });

        btn_sure = (Button) findViewById(R.id.date_select_button_right);
        if (positiveText != null) {
            btn_sure.setVisibility(View.VISIBLE);
            btn_sure.setText(positiveText);
        }
        btn_cancel = (Button) findViewById(R.id.date_select_button_left);
        if (negativeText != null) {
            btn_cancel.setVisibility(View.VISIBLE);
            btn_cancel.setText(negativeText);
        }

        TextView title = (TextView) findViewById(R.id.title);
        title.setText(titleText);
    }

    @Override
    public void setTitle(CharSequence title) {
        titleText = title;
    }

    private void setPositiveButton(CharSequence mPositiveButtonText, View.OnClickListener onClickListener) {
        positiveText = mPositiveButtonText;
        positiveClickListener = onClickListener;// can't use btn_sure here
        // because it's on defined yet
    }

    private void setNegativeButton(CharSequence mNegativeButtonText, View.OnClickListener onClickListener) {
        negativeText = mNegativeButtonText;
        negativeClickListener = onClickListener;// can't use btn_sure here
        // because it's on defined yet
    }

    public HoursAndMinutesDoublePickDialog setDate(Calendar startCalendar, Calendar endCalencder) {
        if (startCalendar == null && endCalencder == null)
            return this;
        int hourStart = startCalendar.get(Calendar.HOUR_OF_DAY);
        int minuteStart = startCalendar.get(Calendar.MINUTE);
        int hourEnd = endCalencder.get(Calendar.HOUR_OF_DAY);
        int minuteEnd = endCalencder.get(Calendar.MINUTE);

        hours_start.setValue(hourStart);
        mins_start.setValue(minuteStart);

        //        hours_end.setMinValue(startCalendar.get(Calendar.HOUR_OF_DAY));// 结束时间不能小于开始时间
        //        mins_end.setMinValue(startCalendar.get(Calendar.MINUTE));// 结束时间不能小于开始时间
        hours_end.setValue(hourEnd);
        mins_end.setValue(minuteEnd);
        return this;
    }

    public Calendar getEndCalendar() {
        endCalendar.set(Calendar.HOUR_OF_DAY, hours_end.getValue());
        endCalendar.set(Calendar.MINUTE, mins_end.getValue());
        return endCalendar;
    }

    private void setEndCalendar(Calendar endCalendar) {
        this.endCalendar = endCalendar;
    }

    public Calendar getStartCalendar() {
        startCalendar.set(Calendar.HOUR_OF_DAY, hours_start.getValue());
        startCalendar.set(Calendar.MINUTE, mins_start.getValue());
        return startCalendar;
    }

    private void setStartCalendar(Calendar startCalendar) {
        this.startCalendar = startCalendar;
    }

    @Override
    public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
        if (picker == hours_start) {// 开始小时改变，限制结束小时
            //            hours_end.setMinValue(hours_start.getValue());
        } else if (picker == mins_start) {// 开始分钟改变，限制结束分钟
            //            mins_end.setMinValue(mins_start.getValue());
        }
    }

    @Override
    public void dismiss() {
        super.dismiss();
    }

    public static class Builder {
        private final DatePickParams P;

        public Builder(Context context) {
            mContext = (Activity) context;
            mContext.setTheme(R.style.SampleTheme_Light_WrapWidth);
            P = new DatePickParams(context);
        }

        public Builder(Context context, Calendar startCalander, Calendar endCalancer) {
            mContext = (Activity) context;
            mContext.setTheme(R.style.SampleTheme_Light_WrapWidth);
            P = new DatePickParams(context, startCalander, endCalancer);
        }

        public Builder setTitle(CharSequence title) {
            P.mTitle = title;
            return this;
        }

        public Builder setIcon(int iconId) {
            P.mIconId = iconId;
            return this;
        }

        public Builder setPositiveButton(CharSequence text, final View.OnClickListener listener) {
            P.mPositiveButtonText = text;
            P.mPositiveButtonListener = listener;
            return this;
        }

        public Builder setNegativeButton(CharSequence text, final View.OnClickListener listener) {
            P.mNegativeButtonText = text;
            P.mNegativeButtonListener = listener;
            return this;
        }

        public HoursAndMinutesDoublePickDialog create() {
            final HoursAndMinutesDoublePickDialog dialog = new HoursAndMinutesDoublePickDialog(P.mContext);
            P.apply(dialog);
            return dialog;
        }
    }

    public static class DatePickParams {
        public final Context mContext;
        public int mIconId;
        public View.OnClickListener mPositiveButtonListener;
        public CharSequence mPositiveButtonText;
        public CharSequence mTitle;
        public Calendar startCalendar;
        public Calendar endCalandar;
        protected CharSequence mNegativeButtonText;
        protected View.OnClickListener mNegativeButtonListener;

        public DatePickParams(Context context) {
            mContext = context;
            startCalendar = Calendar.getInstance();
            endCalandar = Calendar.getInstance();
        }

        public DatePickParams(Context context, Calendar startCalendar, Calendar endCalandar) {
            mContext = context;
            this.startCalendar = startCalendar;
            this.endCalandar = endCalandar;
        }

        public void apply(HoursAndMinutesDoublePickDialog dialog) {
            if (mTitle != null) {
                dialog.setTitle(mTitle);
            }

            if (mPositiveButtonText != null) {
                dialog.setPositiveButton(mPositiveButtonText, mPositiveButtonListener);
            }
            if (mNegativeButtonText != null) {
                dialog.setNegativeButton(mNegativeButtonText, mNegativeButtonListener);
            }
            if (startCalendar != null)
                dialog.setStartCalendar(startCalendar);
            if (endCalandar != null) {
                dialog.setEndCalendar(endCalandar);
            }
        }
    }

}
